package com.shujia.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;

/**
 * @author shujia
 */
public class Demo2StudentToKafka {
    public static void main(String[] args) throws Exception {
        //擦黄健配置文件对象
        Properties properties = new Properties();
        //设置broker列表
        properties.setProperty("bootstrap.servers", "master:9092,node2:9092,node2:9092");

        //对数据进行序列化的类，String
        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        //创建kafka生产者
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        //读取文件，创建文件输入六
        FileReader fileReader = new FileReader("data/students.json");

        //将字符流转换成缓冲六
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String line;
        //循环读取数据
        while ((line = bufferedReader.readLine()) != null) {
            //将数据写入kafka
            ProducerRecord<String, String> student = new ProducerRecord<>("student", line);
            kafkaProducer.send(student);
        }

        //关闭连接
        kafkaProducer.close();
        bufferedReader.close();
        fileReader.close();
    }
}
